package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.article.dtos.ApArticleDto;
import com.heima.model.article.dtos.ApArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppThreadLocalUtil;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2023/3/14 10:06
 * @Version 1.0
 */
@Service
public class ApArticleServiceImpl implements ApArticleService {

    @Autowired
    private ApArticleMapper articleMapper;
    @Autowired
    private ApArticleConfigMapper configMapper;
    @Autowired
    private ApArticleContentMapper contentMapper;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 每页默认显示条数
     */
    public final static int DEFAULT_SIZE = 10;
    /**
     * 每页最大显示条数
     */
    public final static int MAX_SIZE = 50;

    @Override
    public ResponseResult load(ApArticleHomeDto dto, Integer loadType) {
        //处理页数
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = DEFAULT_SIZE;
        }
        size = Math.min(size, MAX_SIZE);

        dto.setSize(size);

        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }

        return ResponseResult.okResult(articleMapper.loadArticles(dto, loadType));
    }

    @Override
    public ResponseResult saveArticle(ApArticleDto articleDto) {
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(articleDto, article);


        article.setPublishTime(new Date());
        if (article.getId() == null) {
            articleMapper.insert(article);
            //保存config
            ApArticleConfig config = new ApArticleConfig(article.getId());
            configMapper.insert(config);

            //保存内容
            ApArticleContent content = new ApArticleContent();
            content.setContent(articleDto.getContent());
            content.setArticleId(article.getId());
            contentMapper.insert(content);
        } else {
            String redKey = BehaviorConstants.READ_BEHAVIOR + article.getId() + "*";
            Set<String> keys = redisTemplate.keys(redKey);

            Integer redCount = 0;

            for (String key : keys) {
                String count = (String) redisTemplate.opsForValue().get(key);
                redCount = redCount + Integer.parseInt(count);
            }
            article.setViews(redCount);

            Integer collectionCount = 0;
            String collectionKey = BehaviorConstants.COLLECTION_BEHAVIOR + article.getId() + "*";
            Set<String> collectionKeys = redisTemplate.keys(collectionKey);
            for (String key : collectionKeys) {
                String value = (String) redisTemplate.opsForHash().get(key, article.getId().toString());
                if (StringUtils.hasText(value)) {
                    collectionCount++;
                }
            }
            article.setCollection(collectionCount);

            //统计点赞数
            Integer likesCount = 0;
            String likesKey = BehaviorConstants.LIKE_BEHAVIOR + article.getId() + "*";
            Set<String> likesKeys = redisTemplate.keys(likesKey);
            if (CollectionUtils.isEmpty(likesKeys)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            for (String key : likesKeys) {
                String value = (String) redisTemplate.opsForHash().get(key, article.getId().toString());
                if (StringUtils.hasText(value)) {
                    likesCount++;
                }
            }
            article.setLikes(likesCount);

            articleMapper.updateById(article);

            ApArticleContent articleContent = contentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, article.getId()));
            articleContent.setContent(articleDto.getContent());
            contentMapper.updateById(articleContent);
        }

        return ResponseResult.okResult(article.getId());
    }

    @Override
    public ResponseResult query(ApArticle apArticle) {
        ApArticle article = articleMapper.selectById(apArticle);
        String jsonString = JSON.toJSONString(article);
        return ResponseResult.okResult(jsonString);
    }


    @Override
    public ResponseResult reload(ArticleInfoDto dto) {
        //校验判断
        if (StringUtils.isEmpty(dto.getArticleId()) || StringUtils.isEmpty(dto.getAuthorId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //初始化字段
        boolean isFollow = false, isLike = false, isUnlike = false, isCollection = false;


        //获取user
        ApUser user = AppThreadLocalUtil.getUser();
        if (ObjectUtils.isEmpty(user)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer userId = user.getId();
        //点赞行为
        Object like = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId() + "", user.getId() + "");
        if (!ObjectUtils.isEmpty(like)) {
            isLike = true;
        }

        //不喜欢行为
        Object unlike = cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId() + "-" + userId + "", dto.getArticleId() + "");
        if (!ObjectUtils.isEmpty(unlike)) {
            isUnlike = true;
        }
        //是否收藏
        Object collection = cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + dto.getArticleId() + "-" + userId + "", dto.getArticleId() + "");
        if (!ObjectUtils.isEmpty(collection)) {
            isCollection = true;
        }
        //是否关注
        Object follow = cacheService.hGet(BehaviorConstants.APUSER_FOLLOW_RELATION + dto.getArticleId(), dto.getAuthorId() + "");
        if (!ObjectUtils.isEmpty(follow)) {
            isFollow = true;
        }
        //返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isfollow", isFollow);
        resultMap.put("islike", isLike);
        resultMap.put("isunlike", isUnlike);
        resultMap.put("iscollection", isCollection);

        return ResponseResult.okResult(resultMap);

    }
}